package com.ebeitech.auction.view.auction;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebeitech.auction.R;
import com.ebeitech.auction.bean.Auction;
import com.ebeitech.auction.bean.AuctionBidder;
import com.ebeitech.auction.bean.AuctionPhase;
import com.ebeitech.auction.bean.AuctionUser;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.service.HttpAuctionServiceRx;
import com.ebeitech.auction.view.homepage.BaseActivity;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.DimenUtils;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.ViewUtil;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/10/30.
 */
public class AuctionDetailActivity extends BaseActivity {

	public static final int TAB_LIVE = 0;//直播
	public static final int TAB_RECORD = 1;//记录
	public static final int TAB_LAND = 2;//地块

	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.btnRight)
	View btnRight;
	@BindView(R.id.titleBar)
	CommonTitleBar titleBar;
	@BindView(R.id.view_top)
	LinearLayout viewTop;

	private Context mContext;
	private Auction mAuction;
	private int mCurrentIndex;
	private String mCurrentIndexName;
	private int mLastIndex;
	private AuctionBidder mAuctionBidder;
	private AuctionPhase mAuctionPhase;
	private int selectBidderPosition = -1;

	private AuctionLiveFragment mLiveFragment;
	private Fragment mRecordFragment;
	private Fragment mLandFragment;

	@OnClick({R.id.btnRight})
	void onBtnRightClick(View v) {
		// 判断是都是最后阶段
		boolean isFinalPhase = false;
		mAuctionPhase = mAuction.getCurrentAuctionPhase();
		List<AuctionPhase> auctionPhases = mAuction.getAuctionPhases();
		int index = -1;
		if (mAuctionPhase != null) {
			index = auctionPhases.indexOf(mAuctionPhase);
		}

		if (index == -1) {
			return;
		}

		if (index != auctionPhases.size() - 1) {
			showChooseDialog();
			return;
		}

		showFinishDialog();
	}

	private void showChooseDialog() {
		List<String> list = new ArrayList<String>();
		list.add("结束阶段");
		list.add("结束竞拍");
		final CommonAlertDialogFragment optionDialog = new CommonAlertDialogFragment();
		optionDialog.setStyle(CommonAlertDialogFragment.DialogStyle.LIST);
		optionDialog.setCancelable(false);
		optionDialog.setTitle(getString(R.string.ebei_options_item, ""));
		optionDialog.setCancelButtonVisible(false);
		optionDialog.setButtonText(getString(R.string.ebei_cancel), "");
		optionDialog.setListMode(CommonAlertDialogFragment.ListMode.OPTION);
		optionDialog.setList(list);
		optionDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == 0) {
					showNextPhaseDialog();
					ViewUtil.dismissDialog(optionDialog);
				} else {
					showFinishDialog();
					ViewUtil.dismissDialog(optionDialog);
				}
			}
		});
		optionDialog.setOkClickListener(new CommonAlertDialogFragment.OnBtnClickListener() {
			@Override
			public void onClick(View v, CommonAlertDialogFragment dialog) {
				ViewUtil.dismissDialog(dialog);
			}
		});
		optionDialog.show(getSupportFragmentManager(), "CommonOptionDialogFragment");
	}

	private void showNextPhaseDialog()
	{
		String message = getString(R.string.ebei_dialog_phase_x_next, mAuction.getCurrentAuctionPhase().getPhaseName());
		ViewUtil.showAlertDialog(mContext, null, message, new CommonAlertDialogFragment.OnBtnClickListener() {
			@Override
			public void onClick(View v, CommonAlertDialogFragment dialog) {
				dialog.dismiss();
				activeNextAuctionPhase(false);
			}
		}, null);
	}
	private void showFinishDialog()
	{
		View view = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_phase_finish_dialog, null);

		final CommonAlertDialogFragment phaseFinishDialog = new CommonAlertDialogFragment();
		phaseFinishDialog.setStyle(CommonAlertDialogFragment.DialogStyle.CUSTOM);
		phaseFinishDialog.setCancelable(false);
		phaseFinishDialog.setTitle(getString(R.string.ebei_dialog_phase_finish));
		phaseFinishDialog.setCancelButtonVisible(false);
		phaseFinishDialog.setButtonText(getString(R.string.ebei_cancel), "");
		phaseFinishDialog.setCustomView(view);
		phaseFinishDialog.setOkClickListener(new CommonAlertDialogFragment.OnBtnClickListener() {
			@Override
			public void onClick(View v, CommonAlertDialogFragment dialog) {
				ViewUtil.dismissDialog(dialog);
			}
		});
		view.findViewById(R.id.view_get).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 本方获取
				mAuctionBidder = mAuction.getOurAuctionBidder();
				if (mAuctionBidder == null || StringUtil.isEmpty(mAuctionBidder.getBidderAuctionCode())) {
					ViewUtil.toastMsg(mContext, R.string.ebei_data_error);
					return;
				}
				finishAuctionPhase();
				ViewUtil.dismissDialog(phaseFinishDialog);
			}
		});
		view.findViewById(R.id.view_not_get).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final List<AuctionBidder> mAuctionBidders = mAuction.getAuctionBidders();
				final List<AuctionBidder> mAuctionBidders2 = new ArrayList<AuctionBidder>();
				final List<String> auctionBidderNames = new ArrayList<String>();
				for (int i = mAuctionBidders.size() - 1;i > -1; i--) {
					AuctionBidder auctionBidder = mAuctionBidders.get(i);
					if (auctionBidder.getIsUs()) {
						continue;
					}
					auctionBidderNames.add(0, StringUtil.getDefaultString(auctionBidder.getBidderAuctionCode())
							+ " " + StringUtil.getDefaultString(auctionBidder.getBidderName()));
					mAuctionBidders2.add(0, auctionBidder);
				}
				AuctionBidder auctionBidder = new AuctionBidder();
				auctionBidder.setBidderAuctionCode("");
				auctionBidder.setBidderName(getString(R.string.ebei_not_company_get_land));
				mAuctionBidders2.add(auctionBidder);
				auctionBidderNames.add(auctionBidder.getBidderName());

				if (auctionBidderNames.size() == 0) {
					return;
				}

				mAuctionBidder = mAuction.getAuctionBidderByCode(SPManager.getInstance().get(mAuction.getAuctionId() + "_" + SPConstants.BIDDER_CODE, ""));
				int index = 0;
				if (mAuctionBidder != null) {
					index = mAuctionBidders2.indexOf(mAuctionBidder);
					if (index == -1) {
						index = 0;
					}
				}
				selectBidderPosition = index;
				mAuctionBidder = mAuctionBidders2.get(selectBidderPosition);

				final CommonAlertDialogFragment unGetDialog = new CommonAlertDialogFragment();
				unGetDialog.setStyle(CommonAlertDialogFragment.DialogStyle.LIST);
				unGetDialog.setCancelable(false);
				unGetDialog.setTitle(getString(R.string.ebei_please_select_company));
				unGetDialog.setList(auctionBidderNames);
				unGetDialog.setListMode(CommonAlertDialogFragment.ListMode.SINGLE);
				unGetDialog.setSelectValue(auctionBidderNames.get(index));
				unGetDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						selectBidderPosition = position;
					}
				});
				unGetDialog.setOkClickListener(new CommonAlertDialogFragment.OnBtnClickListener() {
					@Override
					public void onClick(View v, CommonAlertDialogFragment dialog) {
						// 选择了某个公司
						if (selectBidderPosition == -1) {
							ViewUtil.toastMsg(mContext, getString(R.string.ebei_please_select_company));
							return;
						}
						mAuctionBidder = mAuctionBidders2.get(selectBidderPosition);

						finishAuctionPhase();
						ViewUtil.dismissDialog(dialog);
						ViewUtil.dismissDialog(phaseFinishDialog);
					}
				});
				unGetDialog.setCancelClickListener(new CommonAlertDialogFragment.OnBtnClickListener() {
					@Override
					public void onClick(View v, CommonAlertDialogFragment dialog) {
						ViewUtil.dismissDialog(dialog);
						// 为了兼容IOS,取消的时候把上一个对话框也取消
						ViewUtil.dismissDialog(phaseFinishDialog);
					}
				});
				unGetDialog.show(getSupportFragmentManager(), "CommonSelectDialogFragment");
			}
		});
		phaseFinishDialog.show(getSupportFragmentManager(), "dialog");
	}

	private void activeNextAuctionPhase(final boolean isFinish) {
		HttpService mHttpService = HttpService.getInstance();
		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("auctionId", mAuction.getAuctionId());
		Call<ResponseBody> call = mHttpAuctionServiceRx.activeNextAuctionPhase(params);
		if (isFinish) {
			params.put("auctionBidderCode", mAuctionBidder.getBidderAuctionCode());
			call = mHttpAuctionServiceRx.finishAuction(params);
		}

		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
			}

			@Override
			public void onSuccess(String result) {
				try {
					JSONObject jsonObject = new JSONObject(result);
					if ("-1".equals(jsonObject.optString("ErrorCode"))) {
						String msg = jsonObject.optString("ErrorMsg");
						if (StringUtil.isEmpty(msg)) {
							msg = getString(R.string.ebei_network_load_failure);
						}
						ViewUtil.toastMsg(mContext, msg);
						return;
					}
				} catch (Exception e) {}

				ViewUtil.toastMsg(mContext, R.string.ebei_submit_success);
				// 更新阶段信息
				mAuctionPhase = mAuction.getCurrentAuctionPhase();
				mAuctionPhase.setPhaseState("0");
				List<AuctionPhase> auctionPhases = mAuction.getAuctionPhases();
				int index = -1;
				if (mAuctionPhase != null) {
					index = auctionPhases.indexOf(mAuctionPhase);
				}
				if (index + 1 > -1 && index + 1 < auctionPhases.size()) {
					AuctionPhase auctionPhase = auctionPhases.get(index + 1);
					auctionPhase.setPhaseState("1");
					auctionPhase.setPhaseResult(auctionPhase.getStartPrice());
					auctionPhase.setPhaseOurResult(auctionPhase.getStartPrice());
				}
				if (isFinish) {
					mAuction.setStateCode(CommonConstants.STATE_FINISHED);
				}
				mLiveFragment.setAuction(mAuction);
			}
		}, String.class);
	}

	private void finishAuctionPhase() {
		if (mAuctionBidder == null || (StringUtil.isEmpty(mAuctionBidder.getBidderAuctionCode()) && !getString(R.string.ebei_not_company_get_land).equals(mAuctionBidder.getBidderName()))) {
			ViewUtil.toastMsg(mContext, R.string.ebei_please_select_company);
			return;
		}
		activeNextAuctionPhase(true);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_homepage);
		ButterKnife.bind(this);
		initView();
	}

	private void initView() {
		mContext = this;
		Intent intent = getIntent();
		if (intent != null) {
			mAuction = (Auction) intent.getSerializableExtra(CommonConstants.AUCTION);
			mCurrentIndex = intent.getIntExtra("currentIndex", TAB_LIVE);
		}

		tvTitle.setText(R.string.ebei_auction_detail);
		btnRight.setVisibility(View.GONE);
		// 加载右方点击区域
		int margin = ViewUtil.dp2px(mContext, 20);
		btnRight.setPadding(margin, 0, 0, 0);
		findViewById(R.id.viewPager).setVisibility(View.GONE);
		findViewById(R.id.view_content).setVisibility(View.VISIBLE);

		initRightView();

		mLiveFragment = new AuctionLiveFragment();
		mLiveFragment.setOnChangeListener(new AuctionLiveFragment.OnChangeListener() {
			@Override
			public void onChange(Auction auction) {
				auctionChange(auction);
			}
		});
		mRecordFragment = new AuctionRecordFragment();
		mLandFragment = new AuctionLandFragment();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.add(R.id.view_content, mLandFragment);
		transaction.add(R.id.view_content, mRecordFragment);
		transaction.add(R.id.view_content, mLiveFragment);
		hideFragment(transaction);
		onTabSelected(transaction,0);
		initTopView();
	}

	private void initTopView() {
		String[] tabs = new String[] {
				getString(R.string.ebei_auction_live),
				getString(R.string.ebei_record),
				getString(R.string.ebei_land)
		};
		Integer[] tabIds = new Integer[] {
				R.drawable.ebei_tab_btn_auction_live_selector,
				R.drawable.ebei_tab_btn_record_selector,
				R.drawable.ebei_tab_btn_land_selector
		};

		for (int i = 0; i < tabs.length; i++) {
			View view = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_auction_detail_top, null);
			final TextView tabText = (TextView) view.findViewById(R.id.tvTitleName);
			final ImageView ivImage = (ImageView) view.findViewById(R.id.ivImage);
			final int position = i;
			tabText.setText(tabs[i]);
			ivImage.setImageResource(tabIds[i]);
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mCurrentIndex = position;
					if (mCurrentIndex != mLastIndex) {
						tabText.setSelected(true);
						ivImage.setSelected(true);

						if (mLastIndex > -1) {
							View view = viewTop.getChildAt(mLastIndex);
							TextView tabTextLast = (TextView) view.findViewById(R.id.tvTitleName);
							View ivImageLast = view.findViewById(R.id.ivImage);
							tabTextLast.setSelected(false);
							ivImageLast.setSelected(false);
						}
						FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
						hideFragment(ft);
						onTabSelected(ft,mCurrentIndex);
						mLastIndex = mCurrentIndex;
 						initRightView();
					}
				}
			});
			viewTop.addView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
		}
		mLastIndex = -1;
		viewTop.getChildAt(mCurrentIndex).performClick();
	}

	private void initRightView() {
		boolean isBtnRightVisible = false;
		AuctionUser mAuctionUser = mAuction.getCurrentAuctionUser();
		if (mAuctionUser == null) {
			mAuctionUser = new AuctionUser();
		}
		if (CommonConstants.STATE_BEGINNING.equals(mAuction.getStateCode()) && CommonConstants.AUCTION_USER_BROADCASTER.equals(mAuctionUser.getType())) {
			titleBar.setBtnRightImage(R.drawable.ebei_btn_phase_finish);
			if (mCurrentIndex == TAB_LIVE) {
				isBtnRightVisible = true;
			}
		}
		if (isBtnRightVisible) {
			btnRight.setVisibility(View.VISIBLE);
		} else {
			btnRight.setVisibility(View.GONE);
		}
	}

	public void auctionChange(Auction auction) {
		mAuction = auction;
		initRightView();
	}

	public void onTabSelected(FragmentTransaction transaction,int tab) {
		// TODO Auto-generated method stub

		switch (tab) {
			case TAB_LIVE:
				transaction.show(mLiveFragment);
				break;
			case TAB_RECORD:
				transaction.show(mRecordFragment);
				break;
			case TAB_LAND:
				transaction.show(mLandFragment);
				break;
			default:
				break;
		}
		transaction.commit();
	}

	//隐藏所有的fragment
	public void hideFragment(FragmentTransaction transaction){
		if(mLiveFragment != null){
			transaction.hide(mLiveFragment);
		}
		if(mRecordFragment != null){
			transaction.hide(mRecordFragment);
		}
		if(mLandFragment != null){
			transaction.hide(mLandFragment);
		}
	}


}
